import * as React from 'react';
import { useEffect, useState } from "react";

import styled from 'styled-components';
import { Spin } from 'antd';
import { useNavigate, useLocation } from "react-router-dom";
import { Window } from '@tauri-apps/api/window';
import { setToken } from '../../utils/index';

const parseSearch = (search: string): { [key: string]: any } => {
    let params: { [key: string]: any } = {};

    search.slice(1).split('&').forEach(item => {
        let temp = item.split('=');
        params[temp[0]] = decodeURIComponent(temp[1]);
    });
    return params;
}

export const WxLoginPage = () => {

    const location = useLocation();

    const navigate = useNavigate();

    const [loading, setLoading] = useState<boolean>(true);

    useEffect(() => {
        let searchParams = parseSearch(window.location.search);

        const token: string = searchParams["token"];
        if (!token) {
            //没有token
            setLoading(false);
            navigate('/login');
            return;
        }
        setLoading(false);
        setToken(token);
        // setContextValue("g01_token", token);
        Window.getCurrent().setDecorations(false).then(() => {
            navigate('/login');
        }).catch(() => {
            navigate('/login');
        });
    }, [location.search]);

    if (loading) {
        return (
            <Container>
                <Spin tip="加载中" size="large">
                    {/* <div className={styles.content} /> */}
                </Spin>
            </Container>
        );
    }
    //
    return (
        <Container>
            <Spin tip="校验token" size="large">
                {/* <div className={styles.content} /> */}
            </Spin>
        </Container>
    );
}

const Container = styled.div`
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    width: 100%;
`;

export default WxLoginPage;